home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / vtree < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  46.5 KB  |  1,233 lines

  1. #!/usr/local/bin/gawk -f
  2. #!/usr/bin/awk -f
  3. # vtree: visual directory tree
  4. # @(#) vtree.gawk 2.1 96/12/13
  5. # 90/04    john h. dubois iii (john@armory.com)
  6. # 91/07/01 fixed bug that caused problems when dir given on command line,
  7. #          added some info to help, changed to 4-space indenting
  8. # 96/12/03 Rewrote as all-awk program, using DrawTrees lib.
  9. # 96/12/13 Added s option.
  10.  
  11. BEGIN {
  12.     Name = "vtree"
  13.     Usage = \
  14. "Usage: " Name " [-hastnrAS] [-i<indent>] [-c<columns>] [-w<width>] [dir ...]"
  15.     rcFile = ".vtree"
  16.     ARGC = Opts(Name,Usage,"i>c<w>SaA1rshxt",0, "~/" rcFile ":$HOME/" rcFile,
  17.     "INDENT,COLUMNS,WIDTH,SPACES,ASCII,NOARROW,ONE,ROOT,SORT",
  18.     0,"n",0,"","1,w")
  19.     nIndent = 2
  20.     Width = 10
  21.  
  22.     if ("h" in Options) {
  23.     printf \
  24. "%s: print a visual directory tree.\n"\
  25. "%s\n"\
  26. "%s draws a visual representation of the directory tree rooted at each of\n"\
  27. "the named directories, or the current directory if none is specified.\n"\
  28. "Options:\n"\
  29. "Some of the following options can also be set by assigning values to\n"\
  30. "variables in a configuration file named %s, which is searched for in the\n"\
  31. "invoking user's home directory and in the directory specified by the\n"\
  32. "environment variable UHOME, if it is set (if both files exist, values set\n"\
  33. "in the former take precedence).  Variables are assigned to with the\n"\
  34. "syntax:  varname=value  or in the case of flags, by simply putting the\n"\
  35. "indicated variable name in the file without a value.  Variable names are\n"\
  36. "given in parentheses in the option descriptions.\n"\
  37. "-h: Print this help.\n"\
  38. "-n: Do not read the configuration file.\n"\
  39. "The following options control the manner in which the tree is drawn:\n"\
  40. "-s: Sort each tree by directory names.\n"\
  41. "-t: Prefix each directory name with its index in the tree being printed.\n"\
  42. "-r: Make the displayed tree be rooted at the given directory.  Normally,\n"\
  43. "    the name of the directory is printed by itself before the tree is\n"\
  44. "    displayed in order to save display space.  (ROOT)\n"\
  45. "-i<indent>: The number of character positions to indent when showing the\n"\
  46. "    children of a directory.  The minimum and default is %d. (INDENT)\n"\
  47. "-c<columns>: The display width to use.  Output is truncated to <columns>\n"\
  48. "    columns.  The default is to use one fewer than the width of the user's\n"\
  49. "    terminal. If -C0 is given, the output is not truncated.  (COLUMNS)\n"\
  50. "-w<width>: Set the maximum number of characters that a directory name may\n"\
  51. "    have without being truncated.  The higher <width> is set, the lower the\n"\
  52. "    number of directory levels that will fit on the display.  <width> must\n"\
  53. "    be at least 2.  The default is %d.  (WIDTH)\n"\
  54. "-1: The directory tree is drawn in an alternate format (one directory name\n"\
  55. "    per line).  For this style, <indent> may be set to 1.  (ONE)\n"\
  56. "-a: Normally, the tree is drawn using box-drawing character appropriate to\n"\
  57. "    the type of terminal the program is invoked from.  If the terminal\n"\
  58. "    does not have box-drawing characters available or -a is given, the\n"\
  59. "    tree is drawn using ASCII characters.  (ASCII)\n"\
  60. "-S: Draw the tree using nothing but spaces for indentation.  (SPACES)\n"\
  61. "-A: Do not put an arrow to the left of each directory name.  (NOARROW)\n",
  62.     Name,Usage,Name,rcFile,nIndent,Width
  63.     exit 0
  64.     }
  65.     FS = "/"
  66.     if ("1" in Options)
  67.     Width = 0
  68.     if ("w" in Options && (Width = Options["w"]) < 2) {
  69.     printf "%s: Value given with -w must be at least 2.\n",
  70.     Name > "/dev/stderr"
  71.     exit 1
  72.     }
  73.     Debug = "x" in Options
  74.     Spaces = "S" in Options
  75.     Rooted = "r" in Options
  76.     Sort = "s" in Options
  77.     addInd = "t" in Options
  78.     if ("a" in Options)
  79.     delete ENVIRON["TERM"]
  80.     if (ARGC < 2) {
  81.     ARGV[1] = "."
  82.     ARGC = 2
  83.     }
  84.     SUBSEP = ","    # for debugging printing
  85.     if ("c" in Options)
  86.         maxLength = Options["c"]
  87.     else {
  88.     maxLength = tiget1("cols")
  89.     maxLength = (maxLength == "") ? 79 : (maxLength - 1)
  90.     }
  91.     useArrow = !("A" in Options)
  92.     if ("i" in Options && (nIndent = Options["i"]) < 2 && Width) {
  93.     printf "%s: Value given with -i must be at least 2.\n",
  94.     Name > "/dev/stderr"
  95.     exit 1
  96.     }
  97.     if (Debug)
  98.         print "" > "/dev/stderr"
  99.     for (i = 1; i < ARGC; i++)
  100.     doTree(ARGV[i],nIndent,Width,Spaces,maxLength,useArrow,Rooted,Sort,
  101.     addInd)
  102. }
  103.  
  104. function doTree(dir,nIndent,Width,Spaces,maxLength,Arrow,Rooted,Sort,addInd,
  105. proc,Data,prefix,prefixes,i,indexes,d) {
  106.     # indexes[n] stores the index prefix for level n
  107.     proc = "cd " dir " && exec find . -type d -print 2>/dev/null"
  108.     proc | getline    # discard . line
  109.     if (Rooted) {
  110.     Data[1] = dir
  111.     prefix = 1 SUBSEP
  112.     }
  113.     else
  114.     print "Directory: " dir
  115.     i = 0
  116.     level = 2
  117.     while ((proc | getline) == 1) {
  118.     oprefix = prefix
  119.     oi = i
  120.     if (Debug)
  121.         print "Read: " $0
  122.     d = $NF        # save this because DrawTrees may nuke current line
  123.     if (!Sort && !Rooted && NF == 2 && i) {
  124.         # print major branch whenever a new one starts, to reduce the peak
  125.         # amount of data stored
  126.         list(Data,nIndent,Width,Spaces,maxLength,Arrow,Sort,addInd)
  127.         split("",Data)
  128.         prefix = ""
  129.         i = 0
  130.         level = 2
  131.     }
  132.     else if (NF != level) {
  133.         if (NF < level) {    # went back
  134.         # Retrieve prefix/index for this level
  135.         prefix = prefixes[NF]
  136.         i = indexes[NF]
  137.         }
  138.         else {    # went deeper
  139.         # save current prefix/index for old level
  140.         prefixes[level] = prefix
  141.         indexes[level] = i
  142.         prefix = prefix i SUBSEP
  143.         i = 0
  144.         }
  145.         if (Debug)
  146.         printf \
  147.         "level change: %d -> %d  Prefix: %s -> %s  Index: %s -> %s\n",
  148.         level,NF,oprefix,prefix,oi,i
  149.         level = NF
  150.     }
  151.     ++i
  152.     Data[prefix i] = d
  153.     if (Debug)
  154.         printf "Data[%s] = %s   Dir: %s\n",prefix i,d,$0
  155.     }
  156.     # print last major branch (or whole tree, if sorting)
  157.     list(Data,nIndent,Width,Spaces,maxLength,Arrow,Sort,addInd)
  158.     close(proc)
  159. }
  160.  
  161. # Globals: altChars[]
  162. function list(Data,nIndent,Width,Spaces,maxLength,Arrow,Sort,AddInd,
  163. newData,addInd) {
  164.     if (Debug)
  165.     print "LIST"
  166.     DrawTrees(Data,nIndent,Width,altChars,Spaces,"",Arrow,maxLength,AddInd,Sort)
  167. }
  168.  
  169. ### Start of ProcArgs library
  170. # @(#) ProcArgs 1.10 96/11/16
  171. # 92/02/29 john h. dubois iii (john@armory.com)
  172. # 93/07/18 Added "#" arg type
  173. # 93/09/26 Do not count -h against MinArgs
  174. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  175. #          Removed meaning of "+" or "-" by itself.
  176. # 94/03/08 Added & option and *()< option types.
  177. # 94/04/02 Added NoRCopt to Opts()
  178. # 94/06/11 Mark numeric variables as such.
  179. # 94/07/08 Opts(): Do not require any args if h option is given.
  180. # 94/09/23 Fixed bug that caused fail if -opt<value> given as last arg.
  181. # 95/01/22 Record options given more than once.  Record option num in argv.
  182. # 95/06/08 Added ExclusiveOptions().
  183. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  184. #          Expand $VARNAME at the start of its filenames.
  185. #          Let varname=0 and -option- turn off an option.
  186. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  187. #          of the vars should be searched for in the environment.
  188. #          Check for duplicate rcfiles.
  189. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  190. #          now return various negatives values on error, not just -1, and
  191. #          Opts() may set Err to various positive values, not just 1.
  192. #          Added AllowUnrecOpt.
  193. # 96/05/23 Check type given for & option
  194. # 96/06/15 Re-port to awk
  195. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  196. #          used by other functions.
  197. # 96/10/15 Added OptChars
  198. # 96/11/01 Added exOpts arg to Opts()
  199. # 96/11/16 Added ; type
  200.  
  201. # optlist is a string which contains all of the possible command line options.
  202. # A character followed by certain characters indicates that the option takes
  203. # an argument, with type as follows:
  204. # :    String argument
  205. # ;    Non-empty string argument
  206. # *    Floating point argument
  207. # (    Non-negative floating point argument
  208. # )    Positive floating point argument
  209. # #    Integer argument
  210. # <    Non-negative integer argument
  211. # >    Positive integer argument
  212. # The only difference the type of argument makes is in the runtime argument
  213. # error checking that is done.
  214.  
  215. # The & option is a special case used to get numeric options without the
  216. # user having to give an option character.  It is shorthand for [-+.0-9].
  217. # If & is included in optlist and an option string that begins with one of
  218. # these characters is seen, the value given to "&" will include the first
  219. # char of the option.  & must be followed by a type character other than ":"
  220. # or ";".
  221. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  222.  
  223. # Strings in argv[] which begin with "-" or "+" are taken to be
  224. # strings of options, except that a string which consists solely of "-"
  225. # or "+" is taken to be a non-option string; like other non-option strings,
  226. # it stops the scanning of argv and is left in argv[].
  227. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  228. # If an option takes an argument, the argument may either immediately
  229. # follow it or be given separately.
  230. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  231. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  232. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  233. # this feature had a bug that caused problems in some cases.  See the OptChars
  234. # parameter to explicitly set the option-specifier characters.
  235.  
  236. # If an option that does not take an argument is given,
  237. # an index with its name is created in Options and its value is set to the
  238. # number of times it occurs in argv[].
  239.  
  240. # If an option that does take an argument is given, an index with its name is
  241. # created in Options and its value is set to the value of the argument given
  242. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  243. # If an option that takes an argument is given more than once,
  244. # Options[option-name,"count"] is incremented, and the value is assigned to
  245. # the index (option-name,instance) where instance is 2 for the second occurance
  246. # of the option, etc.
  247. # In other words, the first time an option with a value is encountered, the
  248. # value is assigned to an index consisting only of its name; for any further
  249. # occurances of the option, the value index has an extra (count) dimension.
  250.  
  251. # The sequence number for each option found in argv[] is stored in
  252. # Options[option-name,"num",instance], where instance is 1 for the first
  253. # occurance of the option, etc.  The sequence number starts at 1 and is
  254. # incremented for each option, both those that have a value and those that
  255. # do not.  Options set from a config file have a value of 0 assigned to this.
  256.  
  257. # Options and their arguments are deleted from argv.
  258. # Note that this means that there may be gaps left in the indices of argv[].
  259. # If compress is nonzero, argv[] is packed by moving its elements so that
  260. # they have contiguous integer indices starting with 0.
  261. # Option processing will stop with the first unrecognized option, just as
  262. # though -- was given except that unlike -- the unrecognized option will not be
  263. # removed from ARGV[].  Normally, an error value is returned in this case.
  264. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  265. # be found, so the number of remaining arguments is returned instead.
  266. # If OptChars is not a null string, it is the set of characters that indicate
  267. # that an argument is an option string if the string begins with one of the
  268. # characters.  A string consisting solely of two of the same option-indicator
  269. # characters stops the scanning of argv[].  The default is "-+".
  270. # argv[0] is not examined.
  271. # The number of arguments left in argc is returned.
  272. # If an error occurs, the global string OptErr is set to an error message
  273. # and a negative value is returned.
  274. # Current error values:
  275. # -1: option that required an argument did not get it.
  276. # -2: argument of incorrect type supplied for an option.
  277. # -3: unrecognized (invalid) option.
  278. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  279. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  280. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  281. {
  282. # ArgNum is the index of the argument being processed.
  283. # ArgsLeft is the number of arguments left in argv.
  284. # Arg is the argument being processed.
  285. # ArgLen is the length of the argument being processed.
  286. # ArgInd is the position of the character in Arg being processed.
  287. # Option is the character in Arg being processed.
  288. # Pos is the position in OptList of the option being processed.
  289. # NumOpt is true if a numeric option may be given.
  290.     ArgsLeft = argc
  291.     NumOpt = index(OptList,"&")
  292.     OptionNum = 0
  293.     if (OptChars == "")
  294.     OptChars = "-+"
  295.     while (OptChars != "") {
  296.     c = substr(OptChars,1,1)
  297.     OptChars = substr(OptChars,2)
  298.     OptCharSet[c]
  299.     OptTerm[c c]
  300.     }
  301.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  302.     Arg = argv[ArgNum]
  303.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  304.         break    # Not an option; quit
  305.     if (Arg in OptTerm) {
  306.         delete argv[ArgNum]
  307.         ArgsLeft--
  308.         break
  309.     }
  310.     ArgLen = length(Arg)
  311.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  312.         Option = substr(Arg,ArgInd,1)
  313.         if (NumOpt && Option ~ /[-+.0-9]/) {
  314.         # If this option is a numeric option, make its flag be & and
  315.         # its option string flag position be the position of & in
  316.         # the option string.
  317.         Option = "&"
  318.         Pos = NumOpt
  319.         # Prefix Arg with a char so that ArgInd will point to the
  320.         # first char of the numeric option.
  321.         Arg = "&" Arg
  322.         ArgLen++
  323.         }
  324.         # Find position of flag in option string, to get its type (if any).
  325.         # Disallow & as literal flag.
  326.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  327.         if (AllowUnrecOpt) {
  328.             Escape = 1
  329.             break
  330.         }
  331.         else {
  332.             OptErr = "Invalid option: " specGiven Option
  333.             return -3
  334.         }
  335.         }
  336.  
  337.         # Find what the value of the option will be if it takes one.
  338.         # NeedNextOpt is true if the option specifier is the last char of
  339.         # this arg, which means that if the option requires a value it is
  340.         # the next arg.
  341.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  342.         if (GotValue = ArgNum + 1 < argc)
  343.             Value = argv[ArgNum+1]
  344.         }
  345.         else {    # Value is included with option
  346.         Value = substr(Arg,ArgInd + 1)
  347.         GotValue = 1
  348.         }
  349.  
  350.         if (HadValue = AssignVal(Option,Value,Options,
  351.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  352.         specGiven)) {
  353.         if (HadValue < 0)    # error occured
  354.             return HadValue
  355.         if (HadValue == 2)
  356.             ArgInd++    # Account for the single-char value we used.
  357.         else {
  358.             if (NeedNextOpt) {    # option took next arg as value
  359.             delete argv[++ArgNum]
  360.             ArgsLeft--
  361.             }
  362.             break    # This option has been used up
  363.         }
  364.         }
  365.     }
  366.     if (Escape)
  367.         break
  368.     # Do not delete arg until after processing of it, so that if it is not
  369.     # recognized it can be left in ARGV[].
  370.     delete argv[ArgNum]
  371.     ArgsLeft--
  372.     }
  373.     if (compress != 0) {
  374.     dest = 1
  375.     src = argc - ArgsLeft + 1
  376.     for (count = ArgsLeft - 1; count; count--) {
  377.         ARGV[dest] = ARGV[src]
  378.         dest++
  379.         src++
  380.     }
  381.     }
  382.     return ArgsLeft
  383. }
  384.  
  385. # Assignment to values in Options[] occurs only in this function.
  386. # Option: Option specifier character.
  387. # Value: Value to be assigned to option, if it takes a value.
  388. # Options[]: Options array to return values in.
  389. # ArgType: Argument type specifier character.
  390. # GotValue: Whether any value is available to be assigned to this option.
  391. # Name: Name of option being processed.
  392. # OptionNum: Number of this option (starting with 1) if set in argv[],
  393. #     or 0 if it was given in a config file or in the environment.
  394. # SingleOpt: true if the value (if any) that is available for this option was
  395. #     given as part of the same command line arg as the option.  Used only for
  396. #     options from the command line.
  397. # specGiven is the option specifier character use, if any (e.g. - or +),
  398. # for use in error messages.
  399. # Global variables: OptErr
  400. # Return value: negative value on error, 0 if option did not require an
  401. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  402. # the arg.
  403. # Current error values:
  404. # -1: Option that required an argument did not get it.
  405. # -2: Value of incorrect type supplied for option.
  406. # -3: Bad type given for option &
  407. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  408. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  409.     # If option takes a value...
  410. #    printf "option=<%s> value=<%s>\n",Option,Value
  411.     NumTypes = "*()#<>]"
  412.     if (Option == "&" && ArgType !~ "[" NumTypes) {
  413.     OptErr = "Bad type given for & option"
  414.     return -3
  415.     }
  416.  
  417.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {
  418.     if (!GotValue) {
  419.         if (Name != "")
  420.         OptErr = "Variable requires a value -- " Name
  421.         else
  422.         OptErr = "option requires an argument -- " Option
  423.         return -1
  424.     }
  425.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  426.         OptErr = Err
  427.         return -2
  428.     }
  429.     # Mark this as a numeric variable; will be propogated to Options[] val.
  430.     if (ArgType != ":" && ArgType != ";")
  431.         Value += 0
  432.     if ((Instance = ++Options[Option,"count"]) > 1)
  433.         Options[Option,Instance] = Value
  434.     else
  435.         Options[Option] = Value
  436.     }
  437.     # If this is an environ or rcfile assignment & it was given a value...
  438.     else if (!OptionNum && Value != "") {
  439.     UsedValue = 1
  440.     # If the value is "0" or "-" and this is the first instance of it,
  441.     # do not set Options[Option]; this allows an assignment in an rcfile to
  442.     # turn off an option (for the simple "Option in Options" test) in such
  443.     # a way that it cannot be turned on in a later file.
  444.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  445.         Instance = 1
  446.     else
  447.         Instance = ++Options[Option]
  448.     # Save the value even though this is a flag
  449.     Options[Option,Instance] = Value
  450.     }
  451.     # If this is a command line flag and has a - following it in the same arg,
  452.     # it is being turned off.
  453.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  454.     UsedValue = 2
  455.     if (Option in Options)
  456.         Instance = ++Options[Option]
  457.     else
  458.         Instance = 1
  459.     Options[Option,Instance]
  460.     }
  461.     # If this is a flag assignment without a value, increment the count for the
  462.     # flag unless it was turned off.  The indicator for a flag being turned off
  463.     # is that the flag index has not been set in Options[] but it has an
  464.     # instance count.
  465.     else if (Option in Options || !((Option,1) in Options))
  466.     # Increment number of times this flag seen; will inc null value to 1
  467.     Instance = ++Options[Option]
  468.     Options[Option,"num",Instance] = OptionNum
  469.     return UsedValue
  470. }
  471.  
  472. # Option is the option letter
  473. # Value is the value being assigned
  474. # Name is the var name of the option, if any
  475. # ArgType is one of:
  476. # :    String argument
  477. # ;    Non-null string argument
  478. # *    Floating point argument
  479. # (    Non-negative floating point argument
  480. # )    Positive floating point argument
  481. # #    Integer argument
  482. # <    Non-negative integer argument
  483. # >    Positive integer argument
  484. # specGiven is the option specifier character use, if any (e.g. - or +),
  485. # for use in error messages.
  486. # Returns null on success, err string on error
  487. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  488.     if (ArgType == ":")
  489.     return ""
  490.     if (ArgType == ";") {
  491.     if (Value == "")
  492.         Err = "must be a non-empty string"
  493.     }
  494.     # A number begins with optional + or -, and is followed by a string of
  495.     # digits or a decimal with digits before it, after it, or both
  496.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  497.     Err = "must be a number"
  498.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  499.     Err = "may not include a fraction"
  500.     else if (ArgType ~ "[()<>]" && Value < 0)
  501.     Err = "may not be negative"
  502.     else if (ArgType ~ "[)>]" && Value == 0)
  503.     Err = "must be a positive number"
  504.     if (Err != "") {
  505.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  506.     if (Name != "")
  507.         return ErrStr "variable " substr(Name,1,1) " " Err
  508.     else {
  509.         if (Option == "&")
  510.         Option = Value
  511.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  512.     }
  513.     }
  514.     else
  515.     return ""
  516. }
  517.  
  518. # Note: only the above functions are needed by ProcArgs.
  519. # The rest of these functions call ProcArgs() and also do other
  520. # option-processing stuff.
  521.  
  522. # Opts: Process command line arguments.
  523. # Opts processes command line arguments using ProcArgs()
  524. # and checks for errors.  If an error occurs, a message is printed
  525. # and the program is exited.
  526. #
  527. # Input variables:
  528. # Name is the name of the program, for error messages.
  529. # Usage is a usage message, for error messages.
  530. # OptList the option description string, as used by ProcArgs().
  531. # MinArgs is the minimum number of non-option arguments that this
  532. # program should have, non including ARGV[0] and +h.
  533. # If the program does not require any non-option arguments,
  534. # MinArgs should be omitted or given as 0.
  535. # rcFiles, if given, is a colon-seprated list of filenames to read for
  536. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  537. # by the value of the environment variable HOME.  If a filename begins with
  538. # $, the part from the character after the $ up until (but not including)
  539. # the first character not in [a-zA-Z0-9_] will be searched for in the
  540. # environment; if found its value will be substituted, if not the filename will
  541. # be discarded.
  542. # rcfiles are read in the order given.
  543. # Values given in them will not override values given on the command line,
  544. # and values given in later files will not override those set in earlier
  545. # files, because AssignVal() will store each with a different instance index.
  546. # The first instance of each variable, either on the command line or in an
  547. # rcfile, will be stored with no instance index, and this is the value
  548. # normally used by programs that call this function.
  549. # VarNames is a comma-separated list of variable names to map to options,
  550. # in the same order as the options are given in OptList.
  551. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  552. # searched for in the environment.  If set to -1, all values will be searched
  553. # for in the environment.  Values given in the environment will override
  554. # those given in the rcfiles but not those given on the command line.
  555. # NoRCopt, if given, is an additional letter option that if given on the
  556. # command line prevents the rcfiles from being read.
  557. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  558. # ExclusiveOptions() for a description of exOpts.
  559. # Special options:
  560. # If x is made an option and is given, some debugging info is output.
  561. # h is assumed to be the help option.
  562.  
  563. # Global variables:
  564. # The command line arguments are taken from ARGV[].
  565. # The arguments that are option specifiers and values are removed from
  566. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  567. # The number of elements in ARGV[] should be in ARGC.
  568. # After processing, ARGC is set to the number of elements left in ARGV[].
  569. # The option values are put in Options[].
  570. # On error, Err is set to a positive integer value so it can be checked for in
  571. # an END block.
  572. # Return value: The number of elements left in ARGV is returned.
  573. # Must keep OptErr global since it may be set by InitOpts().
  574. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  575. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  576.     if (MinArgs == "")
  577.     MinArgs = 0
  578.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  579.     optChars)
  580.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  581.     if (ArgsLeft >= 0) {
  582.         OptErr = "Not enough arguments"
  583.         Err = 4
  584.     }
  585.     else
  586.         Err = -ArgsLeft
  587.     printf "%s: %s.\nUse -h for help.\n%s\n",
  588.     Name,OptErr,Usage > "/dev/stderr"
  589.     exit 1
  590.     }
  591.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  592.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  593.     {
  594.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  595.     Err = -e
  596.     exit 1
  597.     }
  598.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  599.     {
  600.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  601.     Err = 1
  602.     exit 1
  603.     }
  604.     return ArgsLeft
  605. }
  606.  
  607. # ReadConfFile(): Read a file containing var/value assignments, in the form
  608. # <variable-name><assignment-char><value>.
  609. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  610. # line and whitespace between the variable name and the assignment character) 
  611. # is stripped.  Lines that do not contain an assignment operator or which
  612. # contain a null variable name are ignored, other than possibly being noted in
  613. # the return value.  If more than one assignment is made to a variable, the
  614. # first assignment is used.
  615. # Input variables:
  616. # File is the file to read.
  617. # Comment is the line-comment character.  If it is found as the first non-
  618. #     whitespace character on a line, the line is ignored.
  619. # Assign is the assignment string.  The first instance of Assign on a line
  620. #     separates the variable name from its value.
  621. # If StripWhite is true, whitespace around the value (whitespace between the
  622. #     assignment char and trailing whitespace on the line) is stripped.
  623. # VarPat is a pattern that variable names must match.  
  624. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  625. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  626. #     a line; no assignment operator is needed.  These variables are set in
  627. #     the output array with a null value.  Lines containing nothing but
  628. #     whitespace are still ignored.
  629. # Output variables:
  630. # Values[] contains the assignments, with the indexes being the variable names
  631. #     and the values being the assigned values.
  632. # Lines[] contains the line number that each variable occured on.  A flag set
  633. #     is record by giving it an index in Lines[] but not in Values[].
  634. # Return value:
  635. # If any errors occur, a string consisting of descriptions of the errors
  636. # separated by newlines is returned.  In no case will the string start with a
  637. # numeric value.  If no errors occur,  the number of lines read is returned.
  638. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  639. FlagsOK,
  640. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  641.     if (Comment != "")
  642.     Comment = "^" Comment
  643.     AssignLen = length(Assign)
  644.     if (VarPat == "")
  645.     VarPat = "."    # null varname not allowed
  646.     while ((Status = (getline Line < File)) == 1) {
  647.     LineNum++
  648.     sub("^[ \t]+","",Line)
  649.     if (Line == "")        # blank line
  650.         continue
  651.     if (Comment != "" && Line ~ Comment)
  652.         continue
  653.     if (Pos = index(Line,Assign)) {
  654.         Var = substr(Line,1,Pos-1)
  655.         Val = substr(Line,Pos+AssignLen)
  656.         if (StripWhite) {
  657.         sub("^[ \t]+","",Val)
  658.         sub("[ \t]+$","",Val)
  659.         }
  660.     }
  661.     else {
  662.         Var = Line    # If no value, var is entire line
  663.         Val = ""
  664.     }
  665.     if (!FlagsOK && Val == "") {
  666.         Errs = Errs \
  667.         sprintf("\nBad assignment on line %d of file %s: %s",
  668.         LineNum,File,Line)
  669.         continue
  670.     }
  671.     sub("[ \t]+$","",Var)
  672.     if (Var !~ VarPat) {
  673.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  674.         LineNum,File,Var)
  675.         continue
  676.     }
  677.     if (!(Var in Lines)) {
  678.         Lines[Var] = LineNum
  679.         if (Pos)
  680.         Values[Var] = Val
  681.     }
  682.     }
  683.     if (Status)
  684.     Errs = Errs "\nCould not read file " File
  685.     close(File)
  686.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  687. }
  688.  
  689. # Variables:
  690. # Data is stored in Options[].
  691. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  692. # Global vars:
  693. # Sets OptErr.  Uses ENVIRON[].
  694. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  695. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  696. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  697. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  698.     split("",filesRead,"")    # make awk know this is an array
  699.     NumVars = split(VarNames,Vars,",")
  700.     TypesInd = Ret = 0
  701.     if (EnvSearch == -1)
  702.     EnvSearch = NumVars
  703.     for (i = 1; i <= NumVars; i++) {
  704.     Var = Vars[i]
  705.     CharOpt = substr(OptList,++TypesInd,1)
  706.     if (CharOpt ~ "^[:;*()#<>&]$")
  707.         CharOpt = substr(OptList,++TypesInd,1)
  708.     Map[Var] = CharOpt
  709.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  710.     # Do not overwrite entries from environment
  711.     if (i <= EnvSearch && Var in ENVIRON &&
  712.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  713.         return Err
  714.     }
  715.  
  716.     numrcFiles = split(rcFiles,fNames,":")
  717.     for (i = 1; i <= numrcFiles; i++) {
  718.     rcFile = fNames[i]
  719.     if (rcFile ~ "^~/")
  720.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  721.     else if (rcFile ~ /^\$/) {
  722.         rcFile = substr(rcFile,2)
  723.         match(rcFile,"^[a-zA-Z0-9_]*")
  724.         envvar = substr(rcFile,1,RLENGTH)
  725.         if (envvar in ENVIRON)
  726.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  727.         else
  728.         continue
  729.     }
  730.     if (rcFile in filesRead)
  731.         continue
  732.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  733.     # may be the same
  734.     filesRead[rcFile]
  735.     if ("x" in Options)
  736.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  737.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  738.     if (retStr > 0)
  739.         READ_RCFILE = 1
  740.     else if (ret != "") {
  741.         OptErr = retStr
  742.         Ret = -1
  743.     }
  744.     for (Var in Lines)
  745.         if (Var in Map) {
  746.         if ((Err = AssignVal(Map[Var],
  747.         Var in Values ? Values[Var] : "",Options,Types[Var],
  748.         Var in Values,Var,0)) < 0)
  749.             return Err
  750.         }
  751.         else {
  752.         OptErr = sprintf(\
  753.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  754.         Lines[Var],rcFile)
  755.         Ret = -1
  756.         }
  757.     }
  758.  
  759.     if ("x" in Options)
  760.     for (Var in Map)
  761.         if (Map[Var] in Options)
  762.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  763.         "/dev/stderr"
  764.         else
  765.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  766.     return Ret
  767. }
  768.  
  769. # OptSets is a semicolon-separated list of sets of option sets.
  770. # Within a list of option sets, the option sets are separated by commas.  For
  771. # each set of sets, if any option in one of the sets is in Options[] AND any
  772. # option in one of the other sets is in Options[], an error string is returned.
  773. # If no conflicts are found, nothing is returned.
  774. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  775. # the exclusions presented by the first set of sets (ab,def,g) if:
  776. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  777. # (a or b is in Options[]) AND (g is in Options) OR
  778. # (d, e, or f is in Options[]) AND (g is in Options)
  779. # An error will be returned due to the exclusions presented by the second set
  780. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  781. # todo: make options given on command line unset options given in config file
  782. # todo: that they conflict with.
  783. function ExclusiveOptions(OptSets,Options,
  784. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  785. SetNum,OSetNum) {
  786.     NumSetSets = split(OptSets,SetSets,";")
  787.     # For each set of sets...
  788.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  789.     # NumSets is the number of sets in this set of sets.
  790.     NumSets = split(SetSets[SetSet],Sets,",")
  791.     # For each set in a set of sets except the last...
  792.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  793.         s1 = Sets[SetNum]
  794.         L1 = length(s1)
  795.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  796.         # If any of the options in this set was given, check whether
  797.         # any of the options in the other sets was given.  Only check
  798.         # later sets since earlier sets will have already been checked
  799.         # against this set.
  800.         if ((c1 = substr(s1,Pos1,1)) in Options)
  801.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  802.             s2 = Sets[OSetNum]
  803.             L2 = length(s2)
  804.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  805.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  806.                 ErrStr = ErrStr "\n"\
  807.                 sprintf("Cannot give both %s and %s options.",
  808.                 c1,c2)
  809.             }
  810.     }
  811.     }
  812.     if (ErrStr != "")
  813.     return substr(ErrStr,2)
  814.     return ""
  815. }
  816.  
  817. ### End of ProcArgs library
  818. ### Start of tinfo lib
  819. # @(#) tinfo 1.0 96/11/30
  820. # altInit(): Get alternate character set terminfo capabilities.
  821. # term, noerror: see tiget().
  822. # tinfo: contains the acsc capability, and any of the enacs, smacs, and rmacs
  823. # capabilities that are defined for the terminal.  Each is indexed by its
  824. # capability name.  enacs is used to enable the alternate character set;
  825. # smacs starts it; rmacs ends it.  acsc is the mapping of vt100 alternate
  826. # character codes to those appropriate for the given terminal.
  827. # AltMap is the acsc string broken down with each alternate character indexed
  828. # by its vt100 equivalent.  num is an ordered list of the vt100 characters
  829. # indexed starting with 1, for applications that need to know what order they
  830. # were given in.
  831. # The global _macs[] is set up with _macs[0] = rmacs & _macs[1] = smacs, for
  832. # use by altPrint().
  833. # The alternate characters and their indexes (vt100 equivalents) are:
  834. # 0  solid square block        a  checker board    f  degree symbol
  835. # g  plus/minus            h  board of squares    j  lower right corner
  836. # k  upper right corner        l  upper left corner    m  lower left corner
  837. # n  plus            q  horizontal line    t  left tee
  838. # u  right tee            v  bottom tee        w  top tee
  839. # x  vertical line        +  arrow pointing right    .  arrow pointing down
  840. # -  arrow pointing up        ,  arrow pointing left    `  diamond
  841. # ~  bullet            I  lantern symbol    o  scan line 1
  842. # s  scan line 9
  843. function altInit(tinfo,term,noerror,AltMap,num,  ret,caplist,acsc,len,j,i) {
  844.     if (ret = tiget("acsc",tinfo,term)) {
  845.     # All other types of errors cause tput to print an informative message
  846.     # to stderr, which is not redirected.
  847.     if (!noerror && ret == 1)
  848.         print "Terminal has no acsc capability." > "/dev/stderr"
  849.     return ret
  850.     }
  851.     caplist = "enacs,smacs,rmacs"
  852.     tiget(caplist,tinfo,term)
  853.     acsc = tinfo["acsc"]
  854.     len = length(acsc)
  855.     j = 0
  856.     for (i = 1; i < len; i += 2)
  857.     AltMap[num[++j] = substr(acsc,i,1)] = substr(acsc,i+1,1)
  858.     if ("rmacs" in tinfo)
  859.     _macs[0] = tinfo["rmacs"]
  860.     if ("smacs" in tinfo)
  861.     _macs[1] = tinfo["smacs"]
  862. }
  863.  
  864. # altPrint: Print characters in either the alternate or standard character set.
  865. # string is the string to print.
  866. # alt should be 1 if string is in the alternate character set; 0 if in the
  867. # standard character set.
  868. # tinfo contains the smacs and rmacs strings, if needed.
  869. # altPrint keeps track of whether the terminal is in the standard or alternate
  870. # character set, and issues smacs and rmacs as needed.
  871. # It should always be called with alt false at the end of program execution to
  872. # ensure that the terminal is left in the standard character set.
  873. # Globals: The character set is tracked in _altPrintSet
  874. function altPrint(string,alt,tinfo) {
  875.     if (alt != _altPrintSet) {
  876.     printf "%s%s",_macs[alt],string
  877.     _altPrintSet = alt
  878.     }
  879.     else
  880.     printf "%s",string
  881. }
  882.  
  883. # tiget: get terminfo capabilities.
  884. # capnames is a comma-separated list of terminfo capabilities to get.
  885. # Each capability is put in tinfo[], indexed by capability name.
  886. # If term is passed, it is the terminal type to get the capabilities for.
  887. # If not, the value of the environment variable TERM is used.
  888. # If noerror is true, error messages are suppressed.
  889. # Return value: the exit status of the last tput, or -1 if term is not passed
  890. # and there is no TERM environment variable.
  891. function tiget(capnames,tinfo,term,noerror,  cmd,RS,ret,names,capname,i) {
  892.     if (term == "")
  893.     if ("TERM" in ENVIRON)
  894.         term = ENVIRON["TERM"]
  895.     else
  896.         return -1
  897.     split(capnames,names,",")
  898.     RS = ""    # this makes the record separator be "\n\n", which hopefully
  899.         # is not very common in terminfo capabilities
  900.     for (i = 1; i in names; i++) {
  901.     capname = names[i]
  902.     cmd = "exec tput -T " term " " capname
  903.     if (noerror)
  904.         cmd = cmd " 2>/dev/null"
  905.     cmd | getline
  906.     if (!(ret = close(cmd)))
  907.         # printf interprets many of the escape chars in the same manner that
  908.         # the terminfo library does... not perfect, but better than nothing
  909.         tinfo[capname] = sprintf($0)
  910.     }
  911.     return ret
  912. }
  913.  
  914. function tiget1(capname,term,noerror,  capnames) {
  915.     delete tinfo[capname]
  916.     tiget(capname,tinfo,term,noerror)
  917.     return tinfo[capname]
  918. }
  919. ### End of tinfo lib
  920. ### Start of DrawTrees lib
  921. # @(#) DrawTrees 1.0 96/11/30
  922. #      Data[] is a tree of data to draw.  The indexes consist of one or more
  923. # integer values separated by SUBSEP.  The "depth" of the element determines
  924. # how many integers (dimensions) are contained in the index.  For each set
  925. # of node siblings, the integer describing the varying dimension varies from
  926. # 1 through n where n is the number of siblings.  This shows the indexes
  927. # used for the elements of a small tree with depth 3:
  928. # 1----+-1,1--+-1,1,1
  929. #      |      |-1,2,2
  930. #      |      \-1,2,3
  931. #      \-1,2--+-1,2,1
  932. #             \-1,2,2
  933. # 2------2,1--+-2,1,1
  934. #             \-2,2,2
  935. #       ^----^--see below
  936. #      The values of the elements are lines of data which constitute the
  937. # nodes of the tree.
  938. #      By default, the tree is drawn with each node on a separate line. 
  939. # Offset is the horizonal offset of each child from its parent.  It must be
  940. # at least 1.  If Width is non-0, the tree is drawn with the first child of
  941. # each parent immediately to the right of its parent.  Width is the number
  942. # of characters allocated to the node data for each level.  If the data for
  943. # an interior node is longer than Width, the value is truncated to Width-1
  944. # characters and a left-tee is appended to indicate the truncation, so Width
  945. # should be at least two.  If this style is used, Offset is the number of
  946. # characters of additional horizontal separation to use after the "split
  947. # point"; in the example tree above, Width is set to 1, causing the addition
  948. # of the characters at the positions marked by ^ on the "see below" line.
  949. #      The tree is drawn using box-drawing characters appropriate to the
  950. # terminal if they are available, and a default set of ASCII characters if
  951. # not.
  952. # If AltChars[] contains all of the following elements, they are used to draw
  953. # the tree.  I is the index to use; A is the ASCII default.
  954. # I A Description
  955. # x | Vertical bar
  956. # q - Horizontal bar
  957. # m \ bottom left corner
  958. # w + Top tee 
  959. # t } Left tee
  960. # + > Right arrow (optional)
  961. # ~ * Bullet (optional)
  962. # If AltChars[] does not contain all of these elements and the alternate
  963. # character set it used, AltChars[] is returned filled in with the
  964. # characters used to draw the tree.  The same array can then be passed back
  965. # to DrawTrees(), avoiding the need for it to use tput again to get the
  966. # terminal's alternate character set capabilities.
  967. # If Spaces is true, indentation is done with spaces only; the effect is to
  968. # set all of the above characters to be a space.
  969. # If term is passed, it overrides the TERM environment variable.  Pass "dumb"
  970. # to force the ASCII values to be used.  
  971. # If the terminal has a right-arrow character defined and useArrow is true,
  972. # it is used for the branch character to the left of node data.
  973. # If maxLength is non-0, output lines are truncated to maxLength characters.
  974. # If AddInd is true, in the output each value is preceded by its index.
  975. # If Sort is true, the tree is sorted by the lexicographical values of its
  976. # elements, and the qsort library must be included in the program.
  977. function DrawTrees(Data,Offset,Width,AltChars,Spaces,term,useArrow,maxLength,
  978. AddInd,Sort,
  979. i,tinfo,Strings,smacs,rmacs,BranchIndent,BlankIndent,bTail,veBar,hoBar,bLeft,
  980. topTee,lTee,arrow,bullet,WidthBar,OffsetBar) {
  981.     if (Spaces) {
  982.     veBar = hoBar = bLeft = topTee = lTee = arrow = " "
  983.     bullet = "*"
  984.     }
  985.     else {
  986.     if ("x" in AltChars && "q" in AltChars && "m" in AltChars && \
  987.     "w" in AltChars && "t" in AltChars) {
  988.         tinfo["smacs"] = AltChars["smacs"]
  989.         tinfo["rmacs"] = AltChars["rmacs"]
  990.         if ("enacs" in AltChars)
  991.         tinfo["enacs"] = AltChars["enacs"]
  992.     }
  993.     else
  994.         altInit(tinfo,term,1,AltChars)
  995.     if ("x" in AltChars && "q" in AltChars && "m" in AltChars && \
  996.     "w" in AltChars && "t" in AltChars) {
  997.         AltChars["smacs"] = smacs = Strings["smacs"] = tinfo["smacs"]
  998.         AltChars["rmacs"] = rmacs = Strings["rmacs"] = tinfo["rmacs"]
  999.         if ("enacs" in tinfo) {
  1000.         printf "%s",tinfo["enacs"]
  1001.         AltChars["enacs"] = tinfo["enacs"]
  1002.         }
  1003.         veBar = AltChars["x"]
  1004.         hoBar = AltChars["q"]
  1005.         bLeft = AltChars["m"]
  1006.         topTee = AltChars["w"]
  1007.         lTee = AltChars["t"]
  1008.         arrow = "+" in AltChars ? AltChars["+"] : hoBar
  1009.         bullet = "~" in AltChars ? AltChars["~"] : lTee
  1010.     }
  1011.     else {
  1012.         # Do not attempt mixing of alt & regular char sets for tree drawing
  1013.         veBar = "|"
  1014.         hoBar = "-"
  1015.         bLeft = "\\"
  1016.         topTee = "+"        # {
  1017.         lTee = "}"
  1018.         arrow = ">"
  1019.         bullet = "*"
  1020.     }
  1021.     }
  1022.     # b: blank indent.  Preceded by newline, followed by branch char.
  1023.     # v: indent that includes a vertical branch on the left:  "|    "
  1024.     #    Preceded by newline or whitespace; followed by branch char.
  1025.     # l: lower left horizontal branch indent.                 "\--->"
  1026.     #    Preceded by newline or whitespace; followed by node data.
  1027.     # t: left tee horizontal branch indent.                   "}--->"
  1028.     #    Preceded by newline or whitespace; followed by node data.
  1029.     # p: Node padding.  Must be adjusted to fit, so is not
  1030.     #    surrounded by smacs/rmacs.  Preceded by node data; followed by branch.
  1031.     # n: Internode branch.  Preceded by branch; followed by node data.  "-->"
  1032.     # tn: Teed internode branch.  Preceded b/branch; followed b/node data."+->"
  1033.     # c: Truncation character.  Followed by branch.
  1034.     # lt: Line truncation character.
  1035.     for (i = Offset + Width; i > 0; i-=1) {
  1036.     BlankIndent = BlankIndent " "
  1037.     BranchIndent = BranchIndent hoBar
  1038.     }
  1039.     WidthIndent = substr(BlankIndent,1,Width)
  1040.     OffsetIndent = substr(BranchIndent,1,Offset)
  1041.     if (BranchIndent != "")
  1042.     bTail = useArrow ? arrow : hoBar
  1043.     Strings["c"] = smacs lTee
  1044.     Strings["lt"] = smacs bullet rmacs
  1045.     Strings["p"] = BranchIndent
  1046.     Strings["n"] = substr(BranchIndent,1,Offset-1) bTail rmacs
  1047.     Strings["tn"] = topTee substr(BranchIndent,1,Offset-2) bTail rmacs
  1048.  
  1049.     Strings["b"] = BlankIndent
  1050.     Strings["v"] = WidthIndent smacs veBar rmacs substr(BlankIndent,1,Offset-1)
  1051.     Strings["l"] = WidthIndent smacs bLeft substr(OffsetIndent,3) bTail rmacs
  1052.     Strings["t"] = WidthIndent smacs lTee  substr(OffsetIndent,3) bTail rmacs
  1053.  
  1054.     dtTraverse(Data,"",Strings,0,"",Width,maxLength,Offset+Width,AddInd,Sort)
  1055. }
  1056.  
  1057. # dtTraverse(): Traverse and print a subtree.
  1058. # Data: as described for DrawTrees().
  1059. # catind: index into Data[] for the parent of this node, followed by a SUBSEP
  1060. #    char.
  1061. # level: The depth of this node, with tree roots at level 0.
  1062. # branch: An indentation string to print the vertical components of the
  1063. #    branches of the siblings of the parents of this node.
  1064. # Return value: 1 if 
  1065. function dtTraverse(Data,catind,Strings,level,branch,Width,Length,levelWidth,
  1066. AddInd,Sort,
  1067. i,ind,siblings,children,nbranch,len,s,subLength,value,k,Arr) {
  1068.     if (Length && (subLength = Length - levelWidth) < 1)
  1069.     # Make sure subLength does not end up 0, which indicates no limit
  1070.     subLength = -1
  1071.     if (Sort) {
  1072.     # build a subtree level to sort
  1073.     for (i = 1; (ind = catind i) in Data; i++)
  1074.         Arr[ind] = Data[ind]
  1075.     qsortArbIndByValue(Arr,k)
  1076.     }
  1077.     for (i = 1; (ind = catind i) in Data; i++) {
  1078.     if (level) {    # Draw indentation string
  1079.         siblings = (catind (i+1)) in Data
  1080.         if (!Width || i != 1)
  1081.         # If parent has not already drawn indent string
  1082.         printf "%s",branch Strings[siblings ? "t" : "l"]
  1083.     }
  1084.     if (Sort)
  1085.         ind = k[i]
  1086.     children = (ind,1) in Data
  1087.     # Print node data
  1088.     value = Data[ind]
  1089.     if (AddInd)
  1090.         value = ind ":" value
  1091.     if (Width && children) {
  1092.         if (subLength == -1) # Won't be able to show children; indicate
  1093.         printf "%.*s%s\n",Length-1,value,Strings["lt"]
  1094.         else {
  1095.         if ((len = length(value)) > Width)
  1096.             printf "%.*s%s",Width-1,value,Strings["c"] # truncate
  1097.         else
  1098.             printf "%s%s%.*s",value,Strings["smacs"], Width-len,
  1099.             Strings["p"]    # pad on right
  1100.         # If this node has children, print offset branch
  1101.         printf "%s",Strings[((ind,2) in Data) ? "tn" : "n"]
  1102.         }
  1103.     }
  1104.     else if (Length)
  1105.         printf "%.*s\n",Length,value
  1106.     else
  1107.         print value
  1108.     if (children && subLength != -1) {
  1109.         if (level)
  1110.         nbranch = branch Strings[siblings ? "v" : "b"]
  1111.         dtTraverse(Data,ind SUBSEP,Strings,level+1,nbranch,Width,subLength,
  1112.         levelWidth,AddInd,Sort)
  1113.     }
  1114.     }
  1115. }
  1116.  
  1117. ### End of DrawTrees lib
  1118. ### Begin qsort routines
  1119.  
  1120. # Arr[] is an array of values with arbitrary indices.
  1121. # k[] is returned with numeric indices 1..n.
  1122. # The values in k[] are the indices of Arr[],
  1123. # ordered so that if Arr[] is stepped through
  1124. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  1125. # through in order of the values of its elements.
  1126. # The return value is the number of elements in the arrays (n).
  1127. function qsortArbIndByValue(Arr,k,  ArrInd,ElNum) {
  1128.     ElNum = 0
  1129.     for (ArrInd in Arr)
  1130.     k[++ElNum] = ArrInd
  1131.     qsortSegment(Arr,k,1,ElNum)
  1132.     return ElNum
  1133. }
  1134.  
  1135. # Sort a segment of an array.
  1136. # Arr[] contains data with arbitrary indices.
  1137. # k[] has indices 1..nelem, with the indices of arr[] as values.
  1138. # This function sorts the elements of arr that are pointed to by
  1139. # k[start..end], swapping the values of elements of k[] so that
  1140. # when this function returns arr[k[start..end]] will be in order.
  1141. function qsortSegment(Arr,k,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  1142.     # handle two-element case explicitly for a tiny speedup
  1143.     if ((end - start) == 1) {
  1144.     if (Arr[tmps = k[start]] > Arr[tmpe = k[end]]) {
  1145.         k[start] = tmpe
  1146.         k[end] = tmps
  1147.     }
  1148.     return
  1149.     }
  1150.     # Make sure comparisons act on these as numbers
  1151.     left = start+0
  1152.     right = end+0
  1153.     sepval = Arr[k[int((left + right) / 2)]]
  1154.     # Make every element <= sepval be to the left of every element > sepval
  1155.     while (left < right) {
  1156.     while (Arr[k[left]] < sepval)
  1157.         left++
  1158.     while (Arr[k[right]] > sepval)
  1159.         right--
  1160.     if (left < right) {
  1161.         tmp = k[left]
  1162.         k[left++] = k[right]
  1163.         k[right--] = tmp
  1164.     }
  1165.     }
  1166.     if (left == right)
  1167.     if (Arr[k[left]] < sepval)
  1168.         left++
  1169.     else
  1170.         right--
  1171.     if (start < right)
  1172.     qsortSegment(Arr,k,start,right)
  1173.     if (left < end)
  1174.     qsortSegment(Arr,k,left,end)
  1175. }
  1176.  
  1177. # Arr[] is an array of values with arbitrary indices.
  1178. # k[] is returned with numeric indices 1..n.
  1179. # The values in k are the indices of Arr[],
  1180. # ordered so that if Arr[] is stepped through
  1181. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  1182. # through in order of the values of its indices.
  1183. # The return value is the number of elements in the arrays (n).
  1184. # If the indexes are numeric, Numeric should be true, so that they can be
  1185. # compared as such rather than as strings.  Numeric indexes do not have to be
  1186. # contiguous.
  1187. function qsortByArbIndex(Arr,k,Numeric,  ArrInd,ElNum) {
  1188.     ElNum = 0
  1189.     if (Numeric)
  1190.     # Indexes do not preserve numeric type, so must be forced
  1191.     for (ArrInd in Arr)
  1192.         k[++ElNum] = ArrInd+0
  1193.     else
  1194.     for (ArrInd in Arr)
  1195.         k[++ElNum] = ArrInd
  1196.     qsortNumIndByValue(k,1,ElNum)
  1197.     return ElNum
  1198. }
  1199.  
  1200. # Arr is an array of elements with contiguous numeric indexes to be sorted
  1201. # by value.
  1202. # start and end are the starting and ending indexes of the range to be sorted.
  1203. function qsortNumIndByValue(Arr,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  1204.     # handle two-element case explicitly for a tiny speedup
  1205.     if ((start - end) == 1) {
  1206.     if ((tmps = Arr[start]) > (tmpe = Arr[end])) {
  1207.         Arr[start] = tmpe
  1208.         Arr[end] = tmps
  1209.     }
  1210.     return
  1211.     }
  1212.     left = start+0
  1213.     right = end+0
  1214.     sepval = Arr[int((left + right) / 2)]
  1215.     while (left < right) {
  1216.     while (Arr[left] < sepval)
  1217.         left++
  1218.     while (Arr[right] > sepval)
  1219.         right--
  1220.     if (left <= right) {
  1221.         tmp = Arr[left]
  1222.         Arr[left++] = Arr[right]
  1223.         Arr[right--] = tmp
  1224.     }
  1225.     }
  1226.     if (start < right)
  1227.     qsortNumIndByValue(Arr,start,right)
  1228.     if (left < end)
  1229.     qsortNumIndByValue(Arr,left,end)
  1230. }
  1231.  
  1232. ### End qsort routines
  1233.